package com.zs.usc.common.log;

import cn.hutool.core.util.ArrayUtil;
import com.zs.usc.common.BusinessException;
import com.zs.usc.common.validate.MyValidate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.groups.Default;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Zero
 * @description 参数校验切面
 * @date 2022/1/10 19:16
 */
@Aspect
@Component
@Slf4j
public class ValidateAspect {


    @Resource
    private LocalValidatorFactoryBean localValidatorFactoryBean;


    // 并且参数类型第一个
    @Before("@annotation(myValidate)")
    public void validateParameter(JoinPoint joinPoint, MyValidate myValidate) {

        // 获取验证参数
        Object[] args = joinPoint.getArgs();

        if (ArrayUtil.isEmpty(args))
            throw new BusinessException("MyValidate注解使用有误！");

        // 验证参数对象
        for (Object arg : args) {
            Set<ConstraintViolation<Object>> validErrors = this.localValidatorFactoryBean.validate(arg, Default.class);
            Iterator<ConstraintViolation<Object>> iterator = validErrors.iterator();
            StringBuilder errorMsg = new StringBuilder();

            // 验证参数对象属性
            while (iterator.hasNext()) {
                // 获取当前对象
                ConstraintViolation<Object> constraintViolation = iterator.next();
                String tagMessage = constraintViolation.getMessageTemplate();
                String error;
                if (StringUtils.isNotBlank(tagMessage) && tagMessage.startsWith("{")) {
                    error = constraintViolation.getPropertyPath() + ":" + constraintViolation.getMessage();
                } else {
                    error = constraintViolation.getMessage();
                }
                errorMsg.append(iterator.hasNext() ? error + "; " : error);
            }

            if (!validErrors.isEmpty()) {
                log.error(errorMsg.toString());
                throw new BusinessException(500, errorMsg.toString());
            }
        }


    }

}



